package com.ihome.android.market2.frag;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.ihome.android.EAFragment;
import com.ihome.android.academy.AlbumAppActivity;
import com.ihome.android.academy.WebViewActivity;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.image.ImageLoader;
import com.ihome.android.image.ImageLoaderFactory;
import com.ihome.android.image.impl.DefaultImageLoadHandler;
import com.ihome.android.academy.R;
import com.ihome.android.market2.asynctask.GetSectionContentTask;
import com.ihome.android.market2.info.TemplateContentInfo;
import com.ihome.android.market2.view.MyScaleItem;
import com.ihome.android.util.ImageHelper;
import com.ihome.android.util.Util;
import com.ihome.android.util.log.LogUtil;

public class AlbumFragment extends EAFragment implements OnClickListener {
	private String						TAG						= AlbumFragment.class.getSimpleName();
	private View						fragview;
	@EAInjectView(id = R.id.rl_main)
	private RelativeLayout				rl_main;

	//	@EAInjectView(id = R.id.iv_inverted_view)
	//	private ImageView					iv_inverted_view;
	@EAInjectView(id = R.id.tv_page_pre)
	private TextView					tv_page_pre;
	@EAInjectView(id = R.id.tv_page_next)
	private TextView					tv_page_next;
	@EAInjectView(id = R.id.ll_data_tip)
	private RelativeLayout ll_data_tip;
	private List<TemplateContentInfo>	mCurPosterList;
	private List<TemplateContentInfo>	mTotalPosterList;
	private int							sapce					= 5;

	private int							focusedPos				= 0;
	private List<MyScaleItem>			mScaleItemList;

	private int							preItemWidth			= 0;
	private int							preItemHeight			= 0;

	private int							totalMarginTop			= 0;
	private int							totalMarginLeft			= 0;
	private int							preMarginLeft			= 0;

	private int							mPreRow					= 0;
	private int							mPreColumn				= 0;

	private int							extraWidth				= 50;
	//	private int							extraWidthCount	= 0;

	private Bitmap						mShadowBitmap			= null;

	/** 更新倒影 */
	private final int					UPDATE_SHADOW			= 0x1000;
	/** 全局Item总数量 */
	private int							globalCount				= 0;
	/** 加载图片 */
	private ImageLoader					imageLoader;
	/** 当前Section ID */
	//	private int							mSectionID		= -1;
	private final int					MSG_SHOW_PREVIEW_PAGE	= 0x1001;
	private final int					MSG_SHOW_NEXT_PAGE		= 0x1002;
	private final int					APPNUM_PER_PAGE			= 8;
	private final int					ITEM_WIDTH				= 300;
	private final int					ITEM_HEIGTH				= 300;
	private final int					ITEM_MARGIN_LEFT		= 20;
	private final int					ITEM_MARGIN_TOP			= 20;
	private int							mCurPage				= 0;
	//	private int							mCurIndex		= 0;
	private int							mAppNum					= 0;
	private int							sectionId				= 0;
	private boolean						isSpecTopic				= false;

	private Handler						mHandler				= new Handler() {
																	public void handleMessage(android.os.Message msg) {
																		switch (msg.what) {
																		case UPDATE_SHADOW:
																			//																	updateShadow(rl_main, iv_inverted_view);
																			break;
																		case MSG_SHOW_PREVIEW_PAGE:
																			ToPrePage();
																			break;
																		case MSG_SHOW_NEXT_PAGE:
																			ToNextPage();
																			break;

																		default:
																			break;
																		}

																	};
																};

	public void setSectionInfo(int sectionId, boolean isSpecTopic) {
		this.sectionId = sectionId;
		this.isSpecTopic = isSpecTopic;
	}

	@Override
	protected void setFragView() {
		mFragView = fragview;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		//		mSectionID = getArguments().getInt(HttpKeys.KEY_SECTIONID, -1);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		imageLoader = ImageLoaderFactory.create(getActivity());
		((DefaultImageLoadHandler) imageLoader.getImageLoadHandler()).setLoadingResources(R.drawable.default_recomm_item);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		LogUtil.d(TAG, " --> onCreateView() position = " + focusedPos);
		fragview = (RelativeLayout) inflater.inflate(R.layout.frag_album_main, container, false);

		initData();
		if (mTotalPosterList == null || mTotalPosterList.size() == 0) {
			Bundle b = new Bundle();
			b.putInt(HttpKeys.KEY_SECTIONID, sectionId);
			new GetSectionContentTask(getActivity(), this).execute(b);
		}
		else {
			initView();
		}
		return fragview;
	}

	@Override
	public void onResume() {
		super.onResume();
		LogUtil.d(TAG, " --> onResume() position = " + focusedPos);
		//setItemOnFocuse();
	}

	private void initData() {
		if (mTotalPosterList == null) {
			mTotalPosterList = new ArrayList<TemplateContentInfo>();
		}
		if (mCurPosterList == null) {
			mCurPosterList = new ArrayList<TemplateContentInfo>();
		}
		if (mScaleItemList == null) {
			mScaleItemList = new ArrayList<MyScaleItem>();
		}
		mTotalPosterList.clear();
		mCurPosterList.clear();
		mScaleItemList.clear();
		mCurPage = 0;
		mAppNum = 0;

		//		rl_main.removeAllViews();
	}

	public void setData(List<TemplateContentInfo> posterList) {
		if(posterList.size()>0){
			ll_data_tip.setVisibility(View.GONE);
		}else{
			ll_data_tip.setVisibility(View.VISIBLE);
		}
		mTotalPosterList = posterList;
		initView();
	}

	private void initView() {
		LogUtil.d(TAG, " --> initView() position = " + focusedPos);
		tv_page_pre.setOnClickListener(this);
		tv_page_next.setOnClickListener(this);
		rl_main.removeAllViews();
		//		extraWidthCount = 0;

		mAppNum = mTotalPosterList.size();
		mCurPage = 1;
		if (mAppNum > APPNUM_PER_PAGE) {
			listCopy(mTotalPosterList, mCurPosterList, 0, APPNUM_PER_PAGE);
		}
		else {
			listCopy(mTotalPosterList, mCurPosterList, 0, mAppNum);
		}

		int index = 0;
		for (TemplateContentInfo info : mCurPosterList) {
			info.setPosition(index);
			addMyScaleView(info);
			index++;
		}

		rl_main.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		int w = rl_main.getMeasuredWidth() + 5 * sapce;
		int h = rl_main.getMeasuredHeight() + 5 * sapce;
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(w, h);
		//params.topMargin = sapce ;
		rl_main.setLayoutParams(params);

	}

	private void addMyScaleView(final TemplateContentInfo info) {
		int width = Util.getWindowWidth(getActivity());

		int widthItemSmall = info.getmWidth() * width / 1920;
		int heightItemSmall = info.getmHeight() * width / 1920;

		int widthItem = widthItemSmall;
		int heightItem = heightItemSmall;

		MyScaleItem scaleItem = new MyScaleItem(getActivity(), this, imageLoader);
		scaleItem.setImgSrc(R.drawable.default_recomm_item);
		scaleItem.setTag(info);
		scaleItem.setImageUrl(info.getPosterUrl());
		scaleItem.setClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				postClick(info);
			}
		});

		if (mScaleItemList.size() < mCurPosterList.size()) {
			mScaleItemList.add(scaleItem);
		}
		rl_main.addView(scaleItem.getView());

		for (TemplateContentInfo preinfo : mCurPosterList) {
			if (info.getmRow() == preinfo.getmRow() && info.getmCol() == (preinfo.getmCol() + 1)) {
				preItemWidth = preinfo.getmWidth() * width / 1920;
				LogUtil.w(TAG, " --> addMyScaleView() preItemWidth = " + preItemWidth);
				break;
			}
		}

		/**
		 * 首先确定所在列，初始化行数据
		 */
		if (info.getmCol() > mPreColumn) {
			totalMarginLeft += (sapce + preItemWidth);
			totalMarginTop = 0;
			mPreRow = 1;
		}
		mPreColumn = info.getmCol();

		/**
		 * 根据行数，累加 marginTop
		 */
		if (info.getmRow() > mPreRow) {
			totalMarginTop += (sapce + preItemHeight);
		}
		mPreRow = info.getmRow();
		preItemHeight = heightItem;
		if (info.getmCol() - 1 > mPreColumn) {
			mPreColumn += info.getmColSpan();
			totalMarginLeft += sapce + widthItem;
		}

		RelativeLayout.LayoutParams tvParams1 = new RelativeLayout.LayoutParams(widthItem, heightItem);
		scaleItem.setTextViewLayout(tvParams1);
		RelativeLayout.LayoutParams rlParams1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		//第一行item 的 Extra
		int topExtra = 18;
		rlParams1.topMargin = totalMarginTop + topExtra;

		//第一列item 的 Extra
		int leftExtra = 18;
		rlParams1.leftMargin = totalMarginLeft + leftExtra;
		scaleItem.setLayoutParams(rlParams1);
	}

	private void updateShadow(View view, ImageView imageView) {
		LogUtil.d(TAG, " --> updateShadow() imageView = " + imageView);

		if (view.getWidth() < 1 || view.getHeight() < 1) {
			return;
		}

		if (mShadowBitmap != null) {
			mShadowBitmap.recycle();
			mShadowBitmap = null;
		}

		mShadowBitmap = ImageHelper.createReflectedImage(view, Util.convertDIP2PX(getActivity(), 100), -65);
		imageView.setImageBitmap(mShadowBitmap);

		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
		params.topMargin = rl_main.getMeasuredHeight() - 85;
		params.height = Util.convertDIP2PX(getActivity(), 100);
		params.width = view.getWidth();
		imageView.setLayoutParams(params);
	}

	private void postClick(TemplateContentInfo info) {
		LogUtil.v(TAG, " --> postClick() info = " + new Gson().toJson(info));
		
		if (isSpecTopic == true) {
			ToWebView(info.getContentId());
		}
		else {
			
			Intent intent = new Intent(getActivity(), AlbumAppActivity.class);
			intent.putExtra(HttpKeys.KEY_SECTIONID, info.getContentId());
			intent.putExtra(AlbumAppActivity.APP_COLLECTION_NAME, info.getName());
			getActivity().startActivity(intent);
		}
	}

	public void setFocusedPosition(int pos) {
		LogUtil.d(TAG, "--> setFocusedPosition() position = " + pos);
		focusedPos = pos;
	}

	//	public boolean isAtTop() {
	//		if (focusedPos < mPosterList.size()) {
	//			TemplateContentInfo info = mPosterList.get(focusedPos);
	//			if (info.getmRow() == 1) {
	//				return true;
	//			}
	//		}
	//		return false;
	//	}

	public void setItemOnFocuse() {
		if (mScaleItemList != null && mScaleItemList.size() > focusedPos) {
			LogUtil.d(TAG, " --> setItemOnFocuse() position = " + focusedPos);
			mScaleItemList.get(focusedPos).getView().requestFocus();
		}
	}

	private void ToNextPage() {
		LogUtil.d(TAG, " --> initView() position = " + focusedPos);
		rl_main.removeAllViews();

		if (mCurPage * APPNUM_PER_PAGE < mAppNum) {
			mCurPage++;
			int startIndex = (mCurPage - 1) * APPNUM_PER_PAGE;

			if ((mCurPage * APPNUM_PER_PAGE) < mAppNum) {
				listCopy(mTotalPosterList, mCurPosterList, startIndex, APPNUM_PER_PAGE);
			}
			else {
				listCopy(mTotalPosterList, mCurPosterList, startIndex, mAppNum - startIndex);
			}
		}

		updateItemViews();
	}

	private void ToPrePage() {
		rl_main.removeAllViews();

		if (mCurPage > 1) {
			mCurPage--;
			listCopy(mTotalPosterList, mCurPosterList, (mCurPage - 1) * APPNUM_PER_PAGE, APPNUM_PER_PAGE);
		}

		updateItemViews();
	}

	private void updateItemViews() {
		int index = 0;
		for (TemplateContentInfo info : mCurPosterList) {
			info.setPosition(index);
			addMyScaleView(info);
			index++;
		}

		rl_main.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		int w = rl_main.getMeasuredWidth() + 5 * sapce;
		int h = rl_main.getMeasuredHeight() + 5 * sapce;
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(w, h);
		//params.topMargin = sapce ;
		rl_main.setLayoutParams(params);

		//		rl_main.requestFocus();
	}

	private void listCopy(List<TemplateContentInfo> src, List<TemplateContentInfo> dst, int start, int num) {
		dst.clear();
		for (int i = 0, j = start; i < num; i++, j++) {
			dst.add(src.get(j));
		}
	}

	@Override
	public void onClick(View v) {
		LogUtil.e(TAG, " --------> onClick() ");
		switch (v.getId()) {
		case R.id.tv_page_pre:
			mHandler.sendEmptyMessage(MSG_SHOW_PREVIEW_PAGE);
			break;
		case R.id.tv_page_next:
			mHandler.sendEmptyMessage(MSG_SHOW_NEXT_PAGE);
			break;
		default:
			break;
		}
	}
	
	private void ToWebView(int contendID) {
		LogUtil.d(TAG, "contendID = " + contendID);
		try {
			Intent intent = new Intent(getActivity(), WebViewActivity.class);
			intent.putExtra(HttpKeys.KEY_SECTIONID, contendID);
			getActivity().startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
